package com.poizon.infrastructure.idem.core.hook;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class IdemThreadPoolHook {

    /**
     * todo: 交给用户定义
     */
    public static void gracefulShutdown(ThreadPoolExecutor threadPoolExecutor) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("[通用幂等框架] 等待线程池任务执行完毕后关闭线程池");
            try {
                threadPoolExecutor.shutdown();
                // 等待所有任务完成，最多等待60秒
                if (!threadPoolExecutor.awaitTermination(300, TimeUnit.SECONDS)) {
                    threadPoolExecutor.shutdownNow();
                }
            } catch (InterruptedException e) {
                threadPoolExecutor.shutdownNow();
            }
            log.info("[通用幂等框架] 线程池任务执行完毕,关闭线程池");
        }));
    }

}
